# -*- coding: utf-8 -*-
# @Author	: changfeng
# @Date		: 2025/9/13 14:26
# @Last Modified by:   changfeng
# @Last Modified time: 2025/9/13 14:26
# Thanks for your comments!
from typing import Optional

from bson import ObjectId

from src.basedata.domain.repositories import AppConfigAbstractRepository
from src.basedata.infrastructure.client.mongodb.repository import MongoDBRepository
from src.basedata.infrastructure.utils import const


class MotorAppConfigRepository(AppConfigAbstractRepository, MongoDBRepository):
    def __init__(self, session):
        MongoDBRepository.__init__(self, session, const.AppConfigTable)

    async def get_basedata_sync_config(self, app_id: Optional[str]):
        query_param = {
            "type": "audit-library",
            "collaborate_type": "SFLZ001",
            "obsoleted": False
        }
        if app_id:
            query_param["app_id"] = ObjectId(app_id)
        pipelines = [
            {
                "$match": query_param
            },
            {
                "$lookup": {
                    "from": "XHHK_Application",
                    "localField": "app_id",
                    "foreignField": "_id",
                    "as": "app"
                }
            },
            {'$unwind': {
                'path': "$app",
                'preserveNullAndEmptyArrays': True
            }},
            {
                "$project": {
                    "name": 1,
                    "value": 1,
                    "options": 1,
                    "app_id": 1,
                    "app.appKey": 1,
                    "app.name": 1,
                    "app.code": 1,
                    "app._id": 1
                }
            }
        ]

        return await self.aggregate(pipeline=pipelines)

    async def get_xhhk_encrypt_config(self, app_id):
        params = {
            "obsoleted": False,
            "app_id": ObjectId(app_id),
            "collaborate_type": "XHHK001",
            "type": "encrypto"
        }

        return await self.query_record(params)
